package org.zero.view;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;

import org.zero.dao.ServerRunStatus;
import org.zero.thread.MainThread;

public class ServerWindow extends JFrame {
	private static final long serialVersionUID = -8856023331302301898L;

	private JLabel titleLabel;
	private JScrollPane scrollPane;
	private JTextArea textArea;
	private JButton stopButton;
	private JButton startButton;

	/**
	 * 用于向文本区域添加信息-不可换行
	 * 
	 * @param msg
	 */
	public void print(String msg) {
		textArea.append(msg);
		textArea.setCaretPosition(textArea.getDocument().getLength()); // 设置滚动在最下面
	}

	/**
	 * 用于向文本区域添加信息-可换行
	 * 
	 * @param msg
	 */
	public void println(String msg) {
		print(msg + "\n");
	}

	// 由JVM进行初始化，保证线程安全
	private static class Instance {
		private static final ServerWindow serverApp = new ServerWindow();
	}

	public static ServerWindow getInstance() {
		return Instance.serverApp;
	}

	private ServerWindow() {
		setSize(430, 560);
		// 在屏幕中居中显示
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

		setTitle("QQ 服务端");
		try {
			setIconImage(ImageIO.read(new File("res/Icon.jpg")));
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "图标文件缺失\n" + e.getMessage(), "错误", JOptionPane.WARNING_MESSAGE);
		}

		init();
		setLayout();
		addListener();
		setVisible(true);
	}

	private void init() {
		titleLabel = new JLabel("QQ 服务器端");
		titleLabel.setFont(new Font("微软雅黑 Light", Font.BOLD, 15));
		titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

		scrollPane = new JScrollPane();

		textArea = new JTextArea();
		// 设置为不可修改
		textArea.setEditable(false);
		scrollPane.setViewportView(textArea);

		startButton = new JButton("Start");
		stopButton = new JButton("Stop");
	}

	private void setLayout() {
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup().addContainerGap()
						.addComponent(startButton, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED, 202, Short.MAX_VALUE)
						.addComponent(stopButton, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
						.addContainerGap())
				.addComponent(titleLabel, GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)
				.addGroup(groupLayout.createSequentialGroup().addContainerGap()
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE).addContainerGap()));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup()
				.addComponent(titleLabel, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
				.addPreferredGap(ComponentPlacement.UNRELATED)
				.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(startButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(stopButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				.addContainerGap()));
		getContentPane().setLayout(groupLayout);
	}

	/**
	 * 添加监听器
	 */
	private void addListener() {
		// 窗口关闭监听
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				int result = JOptionPane.showConfirmDialog(null, "这可是服务器\n确认退出？？？", "请确认", JOptionPane.OK_CANCEL_OPTION,
						JOptionPane.INFORMATION_MESSAGE);
				if (result == JOptionPane.OK_OPTION) {
					MainThread.getInstance().setRunnable(false);
					ServerRunStatus.clearSocket();
					System.exit(0);
				}
			}
		});

		startButton.setActionCommand("start");
		startButton.addActionListener(new ButtonMonitor());

		stopButton.setActionCommand("stop");
		stopButton.addActionListener(new ButtonMonitor());
	}

	private class ButtonMonitor implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			MainThread mainThread = MainThread.getInstance();

			String actionCommand = e.getActionCommand();

			Calendar calendar = null;
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss");

			if ("start".equals(actionCommand)) {
				if (mainThread.isRunnable()) {
					println("服务器已启动，请不要双开！！！");
				} else {
					mainThread.setRunnable(true);
					if (!mainThread.isStart()) {
						mainThread.setStart(true);
						mainThread.start();
					}
					calendar = Calendar.getInstance();
					println("服务器已启动（" + formatter.format(calendar.getTime()) + "）");
				}

			}

			if ("stop".equals(actionCommand)) {
				if (mainThread.isRunnable()) {
					mainThread.setRunnable(false);
					// 清除所有在线用户的 Socket
					ServerRunStatus.clearSocket();
					calendar = Calendar.getInstance();
					println("服务器已停止（" + formatter.format(calendar.getTime()) + "）");
				} else {
					println("服务器正处于停止状态！！！请先启动");
				}
			}
		}

	}
}
